<?php
	$connect = mysqli_connect('localhost','root','root','thinkcmf');
	mysqli_set_charset($connect,'utf8');
	if(!$connect){
		echo jsonReturn(2,'数据库连接失败');
		die;
	}
	// 根据这个字段判断要执行什么操作
	$type = $_GET['type'];
	switch ($type) {
		case 'read':
			$sql = "select * from cmf_school";
			$query = mysqli_query($connect,$sql);
			$data = mysqli_fetch_all($query,MYSQLI_ASSOC);
			//print_r($data);
			echo jsonReturn(1, '学校列表获取成功', $data);
			break;
		case 'add' :
			// 判断请求方式
			$method = $_SERVER['REQUEST_METHOD'];

			if ($method != 'POST') {
				echo jsonReturn(2, '请求方式错误');
			}
			$name = $_POST['name'];
			$city = $_POST['city'];
			$sql = "insert into cmf_school values(NULL, '$name','$city')";
			$res = mysqli_query($connect,$sql);
			if($res){
				echo jsonReturn(1,'添加成功');
			}else{
				echo jsonReturn(2,'添加失败');
			}
			break;
		case 'edit' :
			$id = $_POST['id'];
			$name = $_POST['name'];
			$city = $_POST['city'];
			$sql = "update cmf_school set name='$name',city='$city' where id = $id";
			$update = mysqli_query($connect, $sql);
			if ($update) {
				echo jsonReturn(1,'修改成功');
			} else {
				echo jsonReturn(2,'修改失败');
			}
			break;
		case 'delete' :
			$id = $_GET['id'];
			$sql = "delete from cmf_school where id = $id";
			$res = mysqli_query($connect, $sql);
			if ($res) {
				echo jsonReturn(1,'删除成功');
			}else{
				echo jsonReturn(2,'删除失败');
			}
			break;
        case 'delAll':
            $arr = $_GET['ids'];
            $sql = "delete from cmf_school where id in ($arr)";

            $query = mysqli_query($connect,$sql);
            if ($query) {
                echo "删除成功";
            }else{
                echo "删除失败";
            }
	}


	function jsonReturn($code = 1, $msg = '', $data = [])
	{
		$arr = 
		[
			'code' => $code,
			'msg' => $msg,
			'data' => $data
		];
		return json_encode($arr);
	}

?>